<template>
    <ul class="sidebar-menu menuSet">
        <li class="treeNav slideTop" v-for="(item, index) in dataList" :key="index">
            <div class="link_box">
                <div class="parent_tag">
                    <span class="arrow">
                        <i class="iconfont iconyousanjiao arrowHide"></i>
                        <i class="iconfont iconxiasanjiao arrowShow"></i>
                    </span>
                    <label v-if="selectedMode === 0" :class="{'ivu-checkbox-inner': true, checkInput: true }" @click.stop.prevent="allEquipSel($event)" :equipNo="item.equipNo" :id="item.equipNo"></label>
                    <!-- <i class="iconfont icondian CommunicationOK" v-if="!isCloseStatus"></i> -->
                    <a href="javascript:void(0)" class="equipNoName" :groupId="item.groupId">{{ item.groupName }}
                    </a>
                    <!-- <el-popover placement="bottom" trigger="hover" v-if="isOperation">
                        <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="onAddEquipShow('新增设备', item)">新增设备</el-button>
                        <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="onAddEquipShow('编辑分组', item)">编辑</el-button>
                        <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="onDelFenZu(item)">删除</el-button>
                        <i class="el-icon-more" slot="reference"></i>
                    </el-popover> -->
                </div>
            </div>
            <ul>
                <template>
                    <li :class="{child_tags: true}" v-for="(equipChild, equipChild_id) in item.equipLists" :key="equipChild_id" v-if="equipChild.equipNo != 0" :equipNo="equipChild.equipNo">
                        <label v-if="selectedMode === 0" :class="{'ivu-checkbox-inner': true, checkInput: true}" @click.stop.prevent="radioEquipSel($event.target, 1)" :no="equipChild.equipNo" :setNo="setNo(equipChild.equipNo, equipChild.setNo)" :id="setNo(equipChild.equipNo, equipChild.setNo)"></label>
                        <!-- <i class="iconfont icondian equipNoNameChild" :class="getClass(equipChild.equipState)" v-if="!isCloseStatus"></i> -->
                        <a href="#" @click.stop.prevent="setEquipData(equipChild, $event)">{{ equipChild.equipName }}
                        </a>
                        <!-- <el-popover placement="bottom" trigger="hover" v-if="isOperation">
                            <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="setEquipModel(equipChild)">设为模板</el-button>
                            <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="editEquip(equipChild)">编辑</el-button>
                            <el-button type="danger text primary" size="small" class="elBtn" v-on:click.stop="deleteEquip(item, equipChild)">移除</el-button>
                            <i class="el-icon-more" slot="reference"></i>
                        </el-popover> -->
                    </li>
                    <dynamicMenu v-if="item.children.length > 0" :dataList="item.children" class="parentLevelTwoMenu" :isCloseStatus='isCloseStatus' :selectedMode="selectedMode" :selectedAll="selectedAll" :isOperation="isOperation" :isPage="isPage" :getItem="getItem"></dynamicMenu>
                </template>
            </ul>
        </li>
    </ul>
</template>

<script>
import $ from 'jquery';
export default {
    name: 'dynamicMenu',
    props: {
        dataList: {
            type: Array,
            default: () => []
        },
        isOperation: {
            type: Boolean,
            default: false
        },
        isCloseStatus: {
            type: Boolean,
            default: false
        },
        isPage: {
            type: String,
            default: 'isPage'
        },
        selectedMode: {
            type: Number,
            default: 1
        },
        equipSelected: {
            type: Array,
            default: () => []
        },
        equipNoSelected: {
            type: Array,
            default: () => []
        },
        selectedAll: {
            type: Boolean,
            default: false
        },
        getItem: {
            type: Boolean | Function,
            default: () => []
        }
    },
    data () {
        return {
            selected: '',
            pageNoLeft: 1,
            pageNum: 40,
            nodeLoad: true,
            totalLeft: 1,
            selectedEquip: [],
            setEquipList: [],
            classArr: {}
        };
    },
    beforeRouteUpdate () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },

    // 销毁前
    beforeDestroy () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },

    // 销毁完成
    destroyed () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },
    computed: {
        getClass () {
            return function (state) {
                let className;
                switch (state) {
                    case 0:
                        className = 'NoCommunication';
                        break;
                    case 1:
                        className = 'CommunicationOK';
                        break;
                    case 2:
                        className = 'HaveAlarm';
                        break;
                    case 3:
                        className = 'HaveSetParm';
                        break;
                    case 4:
                        className = 'initial';
                        break;
                    case 5:
                        className = 'CheFang';
                        break;
                    case 6:
                        className = 'BackUp';
                        break;
                    default:
                        className = 'CommunicationOK';
                        break;
                }
                return className;
            };
        },
        setNo () {
            return function (eqNo, setNo) {
                return `${eqNo}.${setNo}`
            }
        }
    },
    mounted () {
        let that = this;
        clearInterval(that.setInter);
        that.setInter = setInterval(function () {
            if (that.selectedAll) {
                $('.menuSet label').addClass('checkInput-active');
            }
            if ($('.slideTop>div')) {
                clearInterval(that.setInter);
            }
            $('.menuSet')
                .off('click')
                .on('click', '.slideTop>.link_box', function (e) {
                    that.showToggle(this);
                    e.stopPropagation();
                });
        }, 500);

        if (this.selectedMode === 1 && this.equipSelected.length > 0) {
            $(`#${this.equipSelected[0].equipNo}]`).addClass('selectedColor');
        }

        // 初始化父类列表
        $('.sidebar-menu .HaveAlarm,.sidebar-menu .NoCommunication')
            .parents('ul')
            .prev('div.link_box')
            .find('i.icondian')
            .removeClass()
            .addClass('iconfont icondian HaveAlarm');

    },
    methods: {
        setSelected () {
            $('.menuSet .checkInput-active').removeClass('checkInput-active');
            if (this.equipNoSelected[0].length > 0) {
                let n = 0;

                this.equipNoSelected[0].forEach((item) => {

                    this.radioEquipSel(`#${item}`, 2);

                    n++;
                    if (n == this.equipNoSelected[0].length) {

                        let isFlag = false,
                            ulDom = $('.checkInput-active').parents('ul:not(.sidebar-menu)'),
                            len = ulDom.length;

                        for (let i = 0; i < len; i++) {

                            // 判断不同结构的层级用不同的方式获取节点
                            isFlag = $(ulDom[i]).children('ul').length === 1 ? this.childrenCheckedNumber($(ulDom[i]).children('ul').children('li').children('div').find('label')) : this.childrenCheckedNumber($(ulDom[i]).find('label'));

                            if (isFlag) {
                                $(ulDom[i])
                                    .prev('div')
                                    .find('label')
                                    .addClass('checkInput-active');
                            } else {
                                $(ulDom[i])
                                    .prev('div')
                                    .find('label')
                                    .removeClass('checkInput-active');
                            }
                        }

                    }

                });
            }

            if (this.equipNoSelected[1].length > 0) {
                for (let item of this.equipNoSelected[1]) {
                    $(`.menuSet label[setno="${item}"]`).addClass('checkInput-active');
                }
            }

        },

        // 新增设备/分组-弹框
        onAddEquipShow (name, item) {
            this.$parent.onAddEquipShow(name, item);
        },

        // 删除分组
        onDelFenZu (item) {
            this.$parent.onDelFenZu(item);
        },

        // 删除设备
        deleteEquip (item, equipChild) {
            this.$parent.deleteEquip(item, equipChild);
        },

        // 不同形态设备选中
        setEquipData (equipChild, e) {
            if (this.selectedMode === 1) {
                if (typeof this.getItem === 'function') {

                    // 当需要选择设备控制项的时候传整个设备信息
                    this.getItem(equipChild);
                }
                $('.child_tags').removeClass('selectedColor');
                $(e.target)
                    .parent()
                    .addClass('selectedColor');
            } else {
                let dom = e.currentTarget.previousElementSibling.previousElementSibling;
                this.radioEquipSel(dom);
            }
        },

        // 分组展开-关闭
        showToggle (dt) {
            if (
                $(dt)
                    .parent()
                    .hasClass('active')
            ) {
                $(dt)
                    .parent()
                    .removeClass('active');
            } else {

                // 判断是否为和设备节点被点击和第一次点击
                if ($(dt).children('.parent_tag').children('label').attr('equipNo') && !$(dt).hasClass('visited')) {

                    let eqNo = $(dt).children('.parent_tag').children('label').attr('equipNo');
                    if (typeof this.getItem === 'function') {

                        // 当需要选择设备控制项的时候传整个设备信息
                        let isChecked = $(dt).children('.parent_tag').children('label').hasClass('checkInput-active');
                        this.getItem(eqNo, isChecked);
                    }

                }
                $(dt).addClass('visited')
                    .parent()
                    .addClass('active');
            }
        },

        // 分组全选
        allEquipSel (dt) {
            let isCheck = $(dt.target).hasClass('checkInput-active'),
                ulDom = $(dt.target).parents('ul'),
                len = ulDom.length,
                isFlag = true;
            if (isCheck) {
                $(dt.target).removeClass('checkInput-active');
                $(dt.target)
                    .parents('div.link_box')
                    .next()
                    .find('label.checkInput')
                    .removeClass('checkInput-active');
            } else {
                $(dt.target).addClass('checkInput-active');
                $(dt.target)
                    .parents('div.link_box')
                    .next()
                    .find('label.checkInput')
                    .addClass('checkInput-active');
            }
            if (
                !$(ulDom[0])
                    .parent()
                    .hasClass('equipList_main')
            ) {
                for (let i = 0; i < len; i++) {
                    isFlag = this.childrenCheckedNumber($(ulDom[i]).find('.checkInput'));
                    if (isFlag) {
                        $(ulDom[i])
                            .prev('div.link_box')
                            .find('label.checkInput')
                            .addClass('checkInput-active');
                    } else {
                        $(ulDom[i])
                            .prev('div.link_box')
                            .find('label.checkInput')
                            .removeClass('checkInput-active');
                    }
                }
            }
            this.equipInfoSelected();
        },

        // 设备选择
        radioEquipSel (that, n) {

            let divDom = $(that).parent('.parent_tag').parent('.link_box').next('ul').find('label'),
                ulDom = $(that).parents('ul:not(.sidebar-menu)'),
                isCheck = $(that).hasClass('checkInput-active'),
                len = ulDom.length;

            // 反选
            isCheck ? $(that).removeClass('checkInput-active') : $(that).addClass('checkInput-active');

            // 把属于该设备下的所有设置勾选
            if (n === 2) {
                isCheck ? $(divDom).removeClass('checkInput-active') : $(divDom).addClass('checkInput-active');
            }

            if (n === 1) {
                let isFlag = false;
                for (let i = 0; i < len; i++) {

                    // 判断不同结构的层级用不同的方式获取节点
                    isFlag = $(ulDom[i]).children('ul').length === 1 ? this.childrenCheckedNumber($(ulDom[i]).children('ul').children('li').children('div').find('label')) : this.childrenCheckedNumber($(ulDom[i]).find('label'));

                    if (isFlag) {
                        $(ulDom[i])
                            .prev('div')
                            .find('label')
                            .addClass('checkInput-active');
                    } else {
                        $(ulDom[i])
                            .prev('div')
                            .find('label')
                            .removeClass('checkInput-active');
                    }
                }
            }

            // this.equipInfoSelected();
        },

        childrenCheckedNumber (dt) {
            let isFlag = true,
                len = dt.length;
            for (let i = 0; i < len; i++) {
                isFlag = $(dt[i]).hasClass('checkInput-active');
                if (!isFlag) break;
            }
            return isFlag;
        },

        // 设备为模板
        setEquipModel (item) {
            this.$parent.setEquipModel(item);
        },

        // 编辑设备
        editEquip (item) {
            let isFlag = true,
                that = this,
                obj = '',
                n = 1;
            while (isFlag) {
                n++;
                if (!obj && n < 10) {
                    that = that.$parent;
                    try {
                        obj = that.init;
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    isFlag = false;
                }
            }
            if (n >= 10) {
                this.$message({
                    showClose: true,
                    message: '子菜单层级过深!',
                    type: 'warning'
                });
                return;
            }
            that.init(item.equipName, 'leftList');
        },

        // 选中设备号
        equipInfoSelected () {
            let arry = [],
                no = 0;
            if ($('.menuSet .checkInput-active')) {
                $('.menuSet .checkInput-active').each((index, item) => {
                    no = $(item).attr('no');
                    if (
                        no &&
                        !arry.some((itemChild, indeChild) => {
                            return no == itemChild;
                        })
                    ) {
                        arry.push(parseInt(no));
                    }
                });
            }
            this.$store.commit('setEquipInfo', arry);
        }
    },
    watch: {
        equipNoSelected (newVal, oldVal) {
            this.$nextTick(() => {
                this.setSelected();
            });
        },
        selectedAll (newVal) {
            if (newVal) {
                $('.menuSet label').addClass('checkInput-active');
            } else {
                $('.menuSet label').removeClass('checkInput-active');
            }
        },
        'dataList': {
            handler: function (val, oval) {
                let that = this;
                this.$nextTick(function () {
                    $('.menuSet .slideTop>div')
                        .unbind()
                        .bind('click', function (e) {
                            that.showToggle(this);
                            e.stopPropagation();
                        });
                });
                this.$forceUpdate();
            },
            deep: true
        }
    }

    // updated () {
    //     for (let item of this.equipNoSelected) {
    //         $(`.menuSet label[equipno=${item}]`).addClass('checkInput-active');
    //         $(`.menuSet label[setno^="${item}."]`).addClass('checkInput-active');
    //     }
    // }
};
</script>
<style lang="scss" src="./menu.scss" scoped></style>